import axios from 'axios'

import router from '@/router/index'
import { ElMessage } from 'element-plus'
import { useShopInfoStore } from "@/store/modules/shopInfo";
import { useRouter, useRoute } from "vue-router";
// axios.defaults.withCredentials = true // 允许携带cookie
axios.defaults.timeout = 60000 // 超时时间
// axios.defaults.headers.common['Authorization'] = '440F84E80BE947E582A1918E77989A2F'
axios.defaults.headers.post['Content-Type'] = 'application/json;charset=utf-8'
//  baseURL: import.meta.env.VITE_BASE_URL,
//     timeout: Number(import.meta.env.VITE_REQUEST_TIME_OUT),
//     withCredentials: false,
const TOKEN_TYPE = 'Bearer '
axios.defaults.headers.post['Content-Type'] = 'application/json'
axios.defaults.headers.put['Content-Type'] = 'application/json'


// 请求拦截器
axios.interceptors.request.use(
    config => {
        const data = config.data || {}
        // const $route = useRoute()
        // const $router = useRouter()
      
        if (window.location.pathname!=='/login') {
            const { token, id } = useShopInfoStore().getterShopInfo
            console.log(' useShopInfoStore().getterShopInfo-----', useShopInfoStore().getterShopInfo)
            config.data = data
            if (token) {
                config.headers.Authorization = TOKEN_TYPE + token
            }
            if (id) {
                config.headers['Shop-Id'] = id
            }
        }
        // axiosCance.addPending(config)
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
// 响应拦截器
axios.interceptors.response.use(response => {
    if ([401, 503].includes(Number(response.data.code))) {
        // console.log('router,', router)
        sessionStorage.setItem('historyUrl', window.location.pathname + window.location.search)
        router.push({ name: 'login' })
    }
    return response
}, error => {
    if ([401, 503].includes(Number(error.response.status))) {
        // console.log('a5')
        // console.log('router,', router)
        sessionStorage.setItem('historyUrl', window.location.pathname + window.location.search)
        // sessionStorage.setItem('webBack', router.que)
        router.push({ name: 'login' })
    } else if (Number(error.response.status) === 403) {
        ElMessage.error(error.response.data.message)
    } else if (error.response.status === 500) {
        if (error.response.data.message.length > 50) {
            ElMessage.error('服务异常！！！')
        } else {
            ElMessage.error(error.response.data.message)
        }
    }
    return Promise.reject(error)
})
